<?php

/**
 * @file
 *
 * Implements a Responsive Images field, similar to the core image field
 */

/**
 * Implements hook_field_formatter_info().
 */
function responsive_images_field_formatter_info() {
  return array(
    'responsive_image' => array(
      'label' => 'Responsive image',
      'description' => t('A responsive image'),
      'field types' => array('image'),
      'settings' => array('image_link' => ''),
    ),
  );
}

/**
 * Implements hook_field_formatter_settings_form().
 *
 * Based on image_field_formatter_settings_form, but without styles
 */
function responsive_images_field_formatter_settings_form($field, $instance, $view_mode, $form, &$form_state) {
  $display = $instance['display'][$view_mode];
  $settings = $display['settings'];

  $link_types = array(
    'content' => t('Content'),
    'file' => t('File'),
  );
  $element['image_link'] = array(
    '#title' => t('Link image to'),
    '#type' => 'select',
    '#default_value' => $settings['image_link'],
    '#empty_option' => t('Nothing'),
    '#options' => $link_types,
  );

  return $element;
}

/**
 * Implements hook_field_formatter_settings_summary().
 *
 * Based on image_field_formatter_settings_form, but without styles
 */
function responsive_images_field_formatter_settings_summary($field, $instance, $view_mode) {
  $display = $instance['display'][$view_mode];
  $settings = $display['settings'];

  $summary = array();
  $summary[] = t('Responsive image');

  $link_types = array(
    'content' => t('Linked to content'),
    'file' => t('Linked to file'),
  );
  // Display this setting only if image is linked.
  if (isset($link_types[$settings['image_link']])) {
    $summary[] = $link_types[$settings['image_link']];
  }

  return implode('<br />', $summary);
}

/**
 * Implements hook_field_formatter_view().
 *
 * Based on image_field_formatter_settings_form, but with 2 styles instead of 1
 */
function responsive_images_field_formatter_view($entity_type, $entity, $field, $instance, $langcode, $items, $display) {
  $element = array();

  // Check if the formatter involves a link.
  if ($display['settings']['image_link'] == 'content') {
    $uri = entity_uri($entity_type, $entity);
  }
  elseif ($display['settings']['image_link'] == 'file') {
    $link_file = TRUE;
  }

  foreach ($items as $delta => $item) {
    if (isset($link_file)) {
      $uri = array(
        'path' => file_create_url($item['uri']),
        'options' => array(),
      );
    }
    $element[$delta] = array(
      '#theme' => 'responsive_images_formatter',
      '#item' => $item,
      '#image_style' => variable_get('responsive_images_small_image_style', 'medium'),
      '#path' => isset($uri) ? $uri : '',
    );
  }

  return $element;
}